package com.yilei.testninegridview

import android.content.Intent
import android.graphics.ImageDecoder
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.provider.MediaStore
import android.util.Log
import android.widget.Button
import androidx.activity.enableEdgeToEdge
import androidx.activity.result.PickVisualMediaRequest
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.obs.services.ObsClient
import com.obs.services.exception.ObsException
import com.obs.services.model.HttpMethodEnum
import com.obs.services.model.PutObjectRequest
import com.obs.services.model.TemporarySignatureRequest
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.io.IOException


class MainActivity : AppCompatActivity() {
    private lateinit var recyclerView: RecyclerView
    private lateinit var adapter: NineGridAdapter
    private val imageUrls = mutableListOf<String>()
    private val mViewModel by lazy { MainViewModel() }
    val PICK_IMAGE_MULTIPLE: Int = 1
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContentView(R.layout.activity_main)
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main)) { v, insets ->
            val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
            insets
        }
        mViewModel.result.observe(this){
            mViewModel.getUrl(it)
        }
        mViewModel.getUrlResult.observe(this){
            imageUrls.add(it)
            adapter.notifyItemInserted(imageUrls.size+1)
        }
        val urls = listOf(
            "http://d.hiphotos.baidu.com/image/h%3D200/sign=201258cbcd80653864eaa313a7dca115/ca1349540923dd54e54f7aedd609b3de9c824873.jpg",
            "http://d.hiphotos.baidu.com/image/h%3D200/sign=ea218b2c5566d01661199928a729d498/a08b87d6277f9e2fd4f215e91830e924b999f308.jpg",
            "http://d.hiphotos.baidu.com/image/h%3D200/sign=ea218b2c5566d01661199928a729d498/a08b87d6277f9e2fd4f215e91830e924b999f308.jpg",
            "http://d.hiphotos.baidu.com/image/h%3D200/sign=201258cbcd80653864eaa313a7dca115/ca1349540923dd54e54f7aedd609b3de9c824873.jpg",
            "http://d.hiphotos.baidu.com/image/h%3D200/sign=201258cbcd80653864eaa313a7dca115/ca1349540923dd54e54f7aedd609b3de9c824873.jpg",
            "http://d.hiphotos.baidu.com/image/h%3D200/sign=201258cbcd80653864eaa313a7dca115/ca1349540923dd54e54f7aedd609b3de9c824873.jpg",
            "http://d.hiphotos.baidu.com/image/h%3D200/sign=201258cbcd80653864eaa313a7dca115/ca1349540923dd54e54f7aedd609b3de9c824873.jpg",
            "http://d.hiphotos.baidu.com/image/h%3D200/sign=201258cbcd80653864eaa313a7dca115/ca1349540923dd54e54f7aedd609b3de9c824873.jpg",
            "http://d.hiphotos.baidu.com/image/h%3D200/sign=201258cbcd80653864eaa313a7dca115/ca1349540923dd54e54f7aedd609b3de9c824873.jpg",
            "http://d.hiphotos.baidu.com/image/h%3D200/sign=201258cbcd80653864eaa313a7dca115/ca1349540923dd54e54f7aedd609b3de9c824873.jpg",
            "http://d.hiphotos.baidu.com/image/h%3D200/sign=201258cbcd80653864eaa313a7dca115/ca1349540923dd54e54f7aedd609b3de9c824873.jpg",
            "http://d.hiphotos.baidu.com/image/h%3D200/sign=201258cbcd80653864eaa313a7dca115/ca1349540923dd54e54f7aedd609b3de9c824873.jpg",
            "http://d.hiphotos.baidu.com/image/h%3D200/sign=201258cbcd80653864eaa313a7dca115/ca1349540923dd54e54f7aedd609b3de9c824873.jpg",
            "https://pictures-6ab5.obs.cn-north-4.myhuaweicloud.com:443/a08b87d6277f9e2fd4f215e91830e924b999f308.jpg?AccessKeyId=7JGRTJOND1JUJQNBVB14&Expires=1728537232&response-content-disposition=inline&response-content-type=application/octet-stream&versionId=null&x-obs-security-token=ggpjbi1ub3J0aC00TiZ7ImFjY2VzcyI6IjdKR1JUSk9ORDFKVUpRTkJWQjE0IiwibWV0aG9kcyI6WyJ0b2tlbiJdLCJyb2xlIjpbXSwicm9sZXRhZ2VzIjpbXSwidGltZW91dF9hdCI6MTcyODU0MDQzODMxOCwidXNlciI6eyJkb21haW4iOnsiaWQiOiIwOTdiMTdjNTljMDAwZjgwMGZkZGMwMDNjZDIwODA4MCIsIm5hbWUiOiJod18wMDg2MTczNjE3MzMzMjBfMDEifSwiaWQiOiIwOTdiMTdjNjhlMDAxMDdiMWY0NGMwMDM2MjM2NmFkMiIsIm5hbWUiOiJod18wMDg2MTczNjE3MzMzMjBfMDEiLCJwYXNzd29yZF9leHBpcmVzX2F0IjoiIiwidXNlcl90eXBlIjoxN319I1aeOviFzGWyRMv-_n-U7LGDUwtixDMiaFpcXBWgTvDYfUAlr0iu6STfr_NIYhQTzMDdG_oygrneM601v0G9WTpFDJgwCobhWqukRXB2apbZMTfvjvXOnW8csZlgr59_NSsqYjeODvS_QDpqBGg5Mzzzljxe-9aFKLPISLLO3iVK6daNXLZQ1aw0OBeiyzuq7NJnGCOu5DRkJrx_gYpWL3x_-qqYQEC_2J4hiiw8Jo2BUm3hBNbtgc7ecY-Ck72GttYRAnmDuIOqKz_FhaoSKzWTOMPpkFrqjQA8yfiDGzlcv_VdhsLUOZmOKgAckc_XmBz7H3SXFG_Hnz2wd5Ebnw%3D%3D&Signature=ZraqRIk%2B8jakD7q7RASrAhsS1ck%3D"
        )
        imageUrls.addAll(urls)
        recyclerView = findViewById(R.id.recyclerView)
        adapter = NineGridAdapter(imageUrls, { index ->
            imageUrls.removeAt(index) // 移除图片
            adapter.notifyItemRemoved(index)
            // 如果需要，通知适配器更新后的项目位置
            adapter.notifyItemRangeChanged(index, imageUrls.size) // 更新后续项的位置
        }, {
//            imageUrls.add("http://d.hiphotos.baidu.com/image/h%3D200/sign=201258cbcd80653864eaa313a7dca115/ca1349540923dd54e54f7aedd609b3de9c824873.jpg")
//            adapter.notifyItemRangeInserted(imageUrls.size-1,1)
            openGallery()
        })
        val spacingInPixels = 10 // 从 dimens.xml 获取间隙值
        recyclerView.addItemDecoration(ItemDecoration(3, spacingInPixels))
        recyclerView.layoutManager = GridLayoutManager(this, 3)
        recyclerView.adapter = adapter
        val btn=findViewById<Button>(R.id.secondBtn)

        val pickMedia = registerForActivityResult(ActivityResultContracts.PickVisualMedia()) { uri ->
            //在用户选择媒体项目或关闭照片选择器后调用回调。
            if (uri != null) {
                val bitmap = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
                    val source = ImageDecoder.createSource(contentResolver, uri)
                    ImageDecoder.decodeBitmap(source){decoder, _, _ ->
                        decoder.allocator = ImageDecoder.ALLOCATOR_SOFTWARE // Force software bitmap
                    }
                } else {
                    MediaStore.Images.Media.getBitmap(contentResolver, uri)
                }
            } else {
                Log.d("PhotoPicker", "No media selected")
            }
        }


        btn.setOnClickListener {
            startActivity(Intent(this,SecondActivity::class.java))

//            val mimeType = "image/gif"
//            pickMedia.launch(PickVisualMediaRequest(ActivityResultContracts.PickVisualMedia.SingleMimeType(mimeType)))
        }
    }

    // 打开图片选择器
    private fun openGallery() {
        val intent = Intent(Intent.ACTION_GET_CONTENT)
        intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true)
        intent.setType("image/*")
        startActivityForResult(Intent.createChooser(intent, "选择图片"), PICK_IMAGE_MULTIPLE)
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode === PICK_IMAGE_MULTIPLE && resultCode === RESULT_OK) {
            data?.let {
                it.clipData?.let {
                    val count: Int = it.getItemCount()
                    for (i in 0 until count) {
                        val imageUri: Uri = it.getItemAt(i).getUri()
                        val mimeType: String = contentResolver.getType(imageUri) ?: ""
                        Log.d("图片位置1", mimeType)
                        var type = ""
                        val types = mimeType.split("/")
                        if (types.isNotEmpty()) {
                            type = types[1]
                            Log.d("图片位置1", type)
                        }
                        imageUri.path?.let {
                            val names=it.split("/")
                            val size=names.size

                            if(names.isNotEmpty()){
                                mViewModel.newUpLoad("${names[size-1]}.${type}", imageUri,contentResolver)
                            }
                        }

                        //imagePathList.add(imageUri.toString())
                    }
                }
                it.data?.let {
                    val imageUri: Uri = data.data!!
                    Log.d("图片位置2", imageUri.toString())

                    //imagePathList.add(imageUri.toString())
                }
            }

        }
    }


}